#!/usr/bin/env python
# -*- coding: utf-8 -*-


import errno
import os
import sys


from subprocess import Popen, PIPE, CalledProcessError


def check_output(*args, **kwargs):
    r"""See check_output documentation in Python 2.7.2, which should
    be compatible, with the exception that this version probably doesn't
    handle binary output.

    >>> check_output(["echo", "hello, world\!"])
    'hello, world\\!\n'

    >>> check_output(["/bin/sh", "-c", "exit 1"])
    Traceback (most recent call last):
    ...
    CalledProcessError: Command '['/bin/sh', '-c', 'exit 1']' returned non-zero exit status 1

    >>> check_output("arg", stdout="something")
    Traceback (most recent call last):
    ...
    ValueError: stdout argument disallowed; used internally

    >>> check_output("arg", stderr="something")
    Traceback (most recent call last):
    ...
    ValueError: stderr argument disallowed; used internally

    >>> check_output("/bin/does_not_exist")
    Traceback (most recent call last):
    ...
    OSError: [Errno 2] No such file or directory
    """

    if 'stdout' in kwargs:
        raise ValueError('stdout argument disallowed; used internally')

    if 'stderr' in kwargs:
        raise ValueError('stderr argument disallowed; used internally')

    p = Popen(*args, stdout=PIPE, stderr=PIPE, **kwargs)
    output, error_output = p.communicate()
    if p.returncode != 0:
        error = CalledProcessError(p.returncode, args[0])
        error.output = output
        print >>sys.stderr, error_output
        raise error
    return str(output.decode("utf-8"))

def makedirs(path):
    try:
        os.makedirs(path)
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass
        else:
            raise    

if __name__ == "__main__":
    import doctest
    doctest.testmod(optionflags=doctest.IGNORE_EXCEPTION_DETAIL)
